<template>
    <div class="auth-container">
      <div class="auth-card">
        <div class="auth-header">
          <h2>图书管理系统登录</h2>
        </div>
        
        <el-tabs v-model="activeTab" stretch class="auth-tabs">
          <el-tab-pane label="密码登录" name="password">
            <el-form 
              :model="loginForm" 
              :rules="loginRules" 
              ref="loginForm" 
              class="auth-form"
            >
              <el-form-item prop="account">
                <el-input
                  v-model="loginForm.account"
                  placeholder="请输入邮箱/用户名"
                  prefix-icon="el-icon-user"
                ></el-input>
              </el-form-item>
              
              <el-form-item prop="password">
                <el-input
                  v-model="loginForm.password"
                  type="password"
                  placeholder="请输入密码"
                  prefix-icon="el-icon-lock"
                  show-password
                ></el-input>
              </el-form-item>
              
              <el-form-item prop="remember">
                <el-checkbox v-model="loginForm.remember">记住我</el-checkbox>
                <el-link type="primary" :underline="false" class="forgot-password">忘记密码?</el-link>
              </el-form-item>
              
              <el-form-item>
                <el-button
                  type="primary"
                  class="auth-button"
                  :loading="loading"
                  @click="handleLogin"
                >登录</el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>
          
          <el-tab-pane label="验证码登录" name="code">
            <el-form 
              :model="codeForm" 
              :rules="codeRules" 
              ref="codeForm" 
              class="auth-form"
            >
              <el-form-item prop="email">
                <el-input
                  v-model="codeForm.email"
                  placeholder="请输入邮箱"
                  prefix-icon="el-icon-message"
                ></el-input>
              </el-form-item>
              
              <el-form-item prop="code">
                <div class="code-input-container">
                  <el-input
                    v-model="codeForm.code"
                    placeholder="请输入验证码"
                    prefix-icon="el-icon-key"
                  ></el-input>
                  <el-button
                    class="send-code-btn"
                    :disabled="codeCountdown > 0"
                    @click="sendCode"
                  >{{ codeCountdown > 0 ? `${codeCountdown}s后重试` : '获取验证码' }}</el-button>
                </div>
              </el-form-item>
              
              <el-form-item>
                <el-button
                  type="primary"
                  class="auth-button"
                  :loading="loading"
                  @click="handleCodeLogin"
                >登录</el-button>
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
        
        <div class="auth-footer">
          <span>还没有账号?</span>
          <el-link type="primary" :underline="false" @click="goRegister">立即注册</el-link>
        </div>
      </div>
    </div>
  </template>
  
  <script>
import axiosInstance from '@/utils/axios';
  export default {
    name: "LoginView",
    data() {
      const validateEmail = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('请输入邮箱'));
        }
        if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value)) {
          return callback(new Error('请输入正确的邮箱格式'));
        }
        callback();
      };
      
      return {
        activeTab: 'password',
        loginForm: {
          account: '88888888',
          password: '123456',
          remember: false
        },
        codeForm: {
          email: '1781499575@qq.com',
          code: ''
        },
        codeCountdown: 0,
        loading: false,
        loginRules: {
          account: [
            { required: true, message: '请输入用户名/邮箱', trigger: 'blur' }
          ],
          password: [
            { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
          ]
        },
        codeRules: {
          email: [
            { validator: validateEmail, trigger: 'blur' }
          ],
          code: [
            { required: true, message: '请输入验证码', trigger: 'blur' },
            { len: 6, message: '验证码长度为6位', trigger: 'blur' }
          ]
        }
      };
    },
    methods: {
      handleLogin() {
        this.$refs.loginForm.validate(valid => {
          if (valid) {
            this.loading = true;
            axiosInstance.post('/login', this.loginForm)
              .then(response => {
                console.log(response.data);

                if(response.data.code === 200){
                  localStorage.setItem('token', response.data.data.token);//存储token到本地存储
                  localStorage.setItem('userInfo', JSON.stringify(response.data.data.user));//存储用户信息到本地存储
                  this.$message.success(response.data.msg); 
                  this.$router.push('/dashboard');
                }else{
                  this.$message.error(response.data.msg);
                  this.loading = false; 
                }
              })
              .catch(error => {
                console.log(error);
              });
          }
        });
      },
      handleCodeLogin() {
        this.$refs.codeForm.validate(valid => {
          if (valid) {
            this.loading = true;
            axiosInstance.get('/login/email', {params: {email: this.codeForm.email, code: this.codeForm.code}})
             .then(response => {
                console.log(response.data); // 打印响应数据
                if(response.data.code === 200){
                  localStorage.setItem('token', response.data.data.token);//存储token到本地存储
                  localStorage.setItem('userInfo', JSON.stringify(response.data.data.userInfo));//存储用户信息到本地存储
                  this.$message.success(response.data.msg); 
                  this.$router.push('/dashboard');
                } 
                else{
                  this.$message.error(response.data.msg);
                  this.loading = false; 
                }
             })
            // 模拟验证码登录请求
            // setTimeout(() => {
            //   this.loading = false;
            //   this.$message.success('登录成功');
            //   this.$router.push('/');
            // }, 1000);
          }
        });
      },
      sendCode() {
        this.$refs.codeForm.validateField('email', valid => {
          if (!valid) {
            this.codeCountdown = 60;
            const timer = setInterval(() => {
              this.codeCountdown--;
              if (this.codeCountdown <= 0) {
                clearInterval(timer);
              }
            }, 1000);
            axiosInstance.get('/login/code', {params: {email: this.codeForm.email}})
            .then(response => {
              console.log(response.data);
              if(response.data.code === 200){
                this.$message.success(response.data.msg);
              }else{
                this.$message.error(response.data.msg);
                this.codeCountdown = 0;
              }
            })
          }
        });
      },
      goRegister() {
        this.$router.push('/register');
      }
    }
  };
  </script>
  
  <style lang="less" scoped>
  .auth-container {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
    background-color: #f5f7fa;
    background-image: linear-gradient(to bottom right, #2c3e50, #34495e);
    
    .auth-card {
      width: 420px;
      padding: 40px;
      background-color: #fff;
      border-radius: 6px;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      // 设置最小高度，根据实际内容调整
      min-height: 450px; 
      
      .auth-header {
        margin-bottom: 30px;
        text-align: center;
        
        h2 {
          color: #2c3e50;
          font-size: 24px;
          font-weight: 500;
        }
      }
      
      .auth-tabs {
        ::v-deep .el-tabs__item {
          font-size: 16px;
          color: #909399;
          
          &.is-active {
            color: #2c3e50;
            font-weight: 500;
          }
        }
        
        ::v-deep .el-tabs__active-bar {
          background-color: #2c3e50;
        }
      }
      
      .auth-form {
        margin-top: 20px;
        
        .forgot-password {
          float: right;
        }
        
        .code-input-container {
          display: flex;
          
          .el-input {
            flex: 1;
            margin-right: 10px;
          }
          
          .send-code-btn {
            width: 120px;
          }
        }
        
        .auth-button {
          width: 100%;
          margin-top: 10px;
          background-color: #2c3e50;
          border-color: #2c3e50;
          
          &:hover {
            background-color: #34495e;
            border-color: #34495e;
          }
        }
      }
      
      .auth-footer {
        margin-top: 20px;
        text-align: center;
        color: #909399;
        
        .el-link {
          margin-left: 5px;
          font-size: 14px;
        }
      }
    }
  }
  </style>
